/***************************************************************************
 *   Copyright (C) 2007 by Phillip Aldridge   *
 *   phillip@imi21.com    *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/


#include <qlabel.h>
#include <qwidget.h>
#include <qmenubar.h>
#include <qlabel.h>
#include <qmessagebox.h>
#include <qlayout.h>
#include <qbuttongroup.h>
#include <qgroupbox.h>
#include <qfile.h>
#include <qvaluelist.h>
#include <qprinter.h>
#include <qpixmap.h>
#include <qsettings.h>
//
#include <qnetwork.h>
#include <qurloperator.h> 
//
#include "meteo2008widget.h"
#include "database.h"
#include "ftp.h"
#include "config.h"
// dialogs
#include "stationdlg.h"
#include "databasedlg.h"
#include "ftpdlg.h"
#include "wundergrunddlg.h"
#include "pathdlg.h"
#include "autodlg.h"

/**
   TODO add timers to trigger automatic archiving
   TODO connect the dialogs and make them work
*/

meteo2008Widget::meteo2008Widget(QWidget* parent, const char* name, WFlags fl)
        : meteo2008WidgetBase(parent,name,fl)
{
   initDefaults();
   initObjects();
   initDefaults();
   initMenu();
   initGUI();
   initDefaults();
   start();
}

meteo2008Widget::~meteo2008Widget()
{
   if (timer) timer->stop ();
#ifndef QT_NO_PRINTER
    delete printer;
#endif
}

/**
   Set the default values
   TODO finish setting default values
*/
void meteo2008Widget::initDefaults()
{

sessionLoad();
}

/**
   start to collect and display data from the database
*/
void meteo2008Widget::start()
{
   testDatabase(); // make this a bool
   database->setStationData( stationdata );
   iconBanner->setStationData( stationdata );
   iconWind->setStationData( stationdata );
   iconTemp->setStationData( stationdata );
   updateDone();

   QDir d1( _STATION_PATH_EXE );
   proc->setWorkingDirectory ( d1 );
   proc->setArguments( "./mysql3600" );
   connect( proc, SIGNAL(processExited()),this, SLOT(updateDone()) );
   connect( timer, SIGNAL(timeout()), this, SLOT(timerRequest()) );
   connect( database, SIGNAL(message(QString)), this, SLOT(message(QString)) );
   connect( graphWeek, SIGNAL(message(QString)), this, SLOT(message(QString)) );
   timer->start( (1000*60*stationUpdate), FALSE );
}

// slot called by timer
void meteo2008Widget::timerRequest()
{
  qDebug("Timer requesting update");
  updateRequest();
}

//
void meteo2008Widget::updateRequest()
{
    if ( !proc->start() )
    {
      qDebug("updateRequest failed");
       kledStation->setColor(Qt::red);
       statusBar->message("Communtication failed with Weather Station",2000 );
       statusStation->setText( tr(" Station error "));
    }else
   {
      qDebug("updateRequest ok");
   kledStation->setColor(Qt::yellow);

      statusBar->message( tr("Requesting data from Weather Station"), 2000 );
      statusStation->setText( tr(" Station transfer "));
    }
}

// slot called by PROC
void meteo2008Widget:: updateDone()
{
   kledStation->setColor(Qt::green);
   statusBar->message( tr("Finished downloading from Weather Station") );
   statusStation->setText( tr(" Station OK "));

   //Archive data each hour
   QString t = QString(QTime::currentTime().toString(QString("hh")));
   qDebug ("Current hour is "+t+","+lastUpdate );
   if (t!=lastUpdate)
   {
      qDebug ("Archiving on the hour" );
      menuArchiveData();
      lastUpdate=t;
   }
//
   updateDisplay();
   updateGraph();
}

/** update the graphviews
   @table : which database table to use
   @days  : number of days to display
*/
void meteo2008Widget::updateGraph()
{

   QString table; 
   int days;
   table=QString("weatherinfo");
   database->setRange();
   graphNow->setWindValues(database->getDayRecords("windspeed",table));
   graphNow->setTempNowValues(database->getDayRecords("temp_out",table));
   graphNow->setRelPressureValues(database->getDayRecords("rel_pressure",table));
   graphNow->setDewpointValues(database->getDayRecords("dewpoint",table));
   graphNow->setHumidityValues(database->getDayRecords("rel_hum_out",table));
   graphNow->update();
//
   graph24h->setWindValues(database->get24Records("windspeedMax"));
   graph24h->setTempNowValues(database->get24Records("tempAvg"));
   graph24h->setTempMaxValues(database->get24Records("tempMax"));
   graph24h->setTempMinValues(database->get24Records("tempMin"));
   graph24h->setRelPressureValues(database->get24Records("rel_pressureAvg"));
   graph24h->setDewpointValues(database->get24Records("dewpointAvg"));
   graph24h->setHumidityValues(database->get24Records("rel_hum_outAvg "));
   graph24h->setRainValues(database->get24Records("rainfall"));

   graph24h->update();
//
   table=QString("days");
   days=15;
graphWeek->setWindValues(database->getDailyRecords("windspeedMax",table,days));
graphWeek->setTempNowValues(database->getDailyRecords("tempAvg",table,days));
graphWeek->setTempMinValues(database->getDailyRecords("tempMin",table,days));
graphWeek->setTempMaxValues(database->getDailyRecords("tempMax",table,days));
graphWeek->setRelPressureValues(database->getDailyRecords("rel_pressureMax",table,days));
graphWeek->setDewpointValues(database->getDailyRecords("dewpointAvg",table,days));
graphWeek->setHumidityValues(database->getDailyRecords("rel_hum_outAvg",table,days));
graphWeek->setRainValues(database->getDailyRecords("rainfall",table,days));
graphWeek->update();
//

days=60;
graphMonth->setWindValues(database->getDailyRecords("windspeedMax",table,days));
graphMonth->setTempNowValues(database->getDailyRecords("tempAvg",table,days));
graphMonth->setTempMinValues(database->getDailyRecords("tempMin",table,days));
graphMonth->setTempMaxValues(database->getDailyRecords("tempMax",table,days));
graphMonth->setRelPressureValues(database->getDailyRecords("rel_pressureMax",table,days));
graphMonth->setDewpointValues(database->getDailyRecords("dewpointAvg",table,days));
graphMonth->setHumidityValues(database->getDailyRecords("rel_hum_outAvg",table,days));graphMonth->setRainValues(database->getDailyRecords("rainfall",table,days));
graphMonth->update();
//

days=365;
graphYear->setWindValues(database->getDailyRecords("windspeedMax",table,days));
graphYear->setTempNowValues(database->getDailyRecords("tempAvg",table,days));
graphYear->setTempMaxValues(database->getDailyRecords("tempMax",table,days));
graphYear->setTempMinValues(database->getDailyRecords("tempMin",table,days));
graphYear->setRainValues(database->getDailyRecords("rainfall",table,days));
graphYear->setDewpointValues(database->getDailyRecords("dewpointAvg",table,days));
graphYear->setHumidityValues(database->getDailyRecords("rel_hum_outAvg",table,days));
graphYear->setRelPressureValues(database->getDailyRecords("rel_pressureMax",table,days));
graphYear->update();
//
days=90;
graphCustom->setWindValues(database->getDailyRecords("windspeedMax",table,days));
graphCustom->setTempNowValues(database->getDailyRecords("tempAvg",table,days));
graphCustom->setTempMaxValues(database->getDailyRecords("tempMax",table,days));
graphCustom->setTempMinValues(database->getDailyRecords("tempMin",table,days));
graphCustom->setRainValues(database->getDailyRecords("rainfall",table,days));
graphCustom->setDewpointValues(database->getDailyRecords("dewpointAvg",table,days));
graphCustom->setHumidityValues(database->getDailyRecords("rel_hum_outAvg",table,days));
graphCustom->setRelPressureValues(database->getDailyRecords("rel_pressureMax",table,days));
graphCustom->update();
}
/**
   Update all the labels
   this is seperate from UPDATEDONE
   so that it can be called to redraw graphs
   and not calling the statin update
*/
void meteo2008Widget::updateDisplay()
{
   qDebug("Updating display");

   database->getLatestRecord();
   // Set left side labels
   labForecastDate->setText(tr( "Date")+" : "+ stationdata->date() );
   labForecastTime->setText(tr( "Time")+" : "+stationdata->time() );
   labForecast->setText(tr( "Forecast")+" : "+stationdata->forecast() );
   labTendency->setText(tr( "Tendency")+" : "+stationdata->tendency() );
   //temperature
   labTempOutside->setText(QString("Outside : %1").arg(stationdata->tempOut()) );
   labTempInside->setText(QString("Inside : %1").arg(stationdata->tempIn() ) );
   labTempMax->setText(QString("Max : %1 at %2").arg(stationdata->tempMax()).arg(stationdata->tempMaxTime())  );
   labTempMin->setText(QString("Min : %1 at %2").arg(stationdata->tempMin()).arg(stationdata->tempMinTime())  );
   //pressure
   labAbsPressure->setText("Abs :"+stationdata->absPressure() );
   labRelPressure->setText("Rel :"+stationdata->relPressure() );
   //rain
   labRain1h->setText(QString("1h : "+stationdata->rain1h()) );
   labRain24h->setText(QString("24h : "+stationdata->rain24h() ) );
   labRain1w->setText(QString("Week : "+stationdata->rain1w() ) );
   labRain1m->setText(QString("Month : "+stationdata->rain1m() ) );
   labRainTotal->setText(QString("Total : "+stationdata->rainTotal() ) );

   //wind
   labWindChill->setText(QString("Chill : "+ stationdata->windChill()+_UNIT_TEMP) );
   labWindDirection->setText("Direction : "+ QString(stationdata->windDirection()) );
   labWindAngle->setText(QString("Angle : %1  Deg").arg(stationdata->windAngle()) );
   labWindSpeed->setText(QString("Speed : %1 %2").arg(stationdata->windSpeed()).arg(_UNIT_SPEED) );

   // humidity
   labDewpoint->setText(QString("Dewpoint : %1").arg(stationdata->dewpoint()) );
   labRelHumIn->setText(QString("In : "+stationdata->relHumIn()) );
   labRelHumOut->setText(QString("Out : "+stationdata->relHumOut()) );

// WIND ICON
   iconWind->update();

// TEMP ICON
   iconTemp->update();

// Forecast icon
   iconForecast->set( stationdata->forecast());

// Web banner icon
   iconBanner->update();
}

void meteo2008Widget::testDatabase()
{
   if (database->open())
   {
      statusDatabase->setText( tr(" Database connected "));
      kledDatabase->setColor(Qt::green);
   }else
   {
      statusDatabase->setText( tr(" Database error "));
      kledDatabase->setColor(Qt::red);
   }
}

void meteo2008Widget::initObjects()
{
   qDebug("Setting up Objects");

   lastUpdate = QString("00");

   kledStation= new KLed(this);
   kledDatabase = new KLed(this);
   stationdata = new StationData();
   database = new Database(this);

   graphNow = new GraphView(this);

   graph24h = new GraphView(this);
   graphWeek = new GraphView(this);
   graphMonth = new GraphView(this);
   graphYear = new GraphView(this);
   graphCustom = new GraphView(this);
   textView = new QTextEdit( this );
   iconWind=new IconWind(this);
   iconTemp=new IconTemp(this);
   iconForecast = new IconForecast(this);
   iconBanner = new IconBanner(this);

   proc = new QProcess( this );
   timer = new QTimer( this );
   ftp = new FTP();
//
#ifndef QT_NO_PRINTER
    printer = new QPrinter;
#endif
//
   statusBar = new QStatusBar(this);
}

void meteo2008Widget::initGUI()
{

qDebug("Setting up GUI");

   QBoxLayout* topLayout = new QVBoxLayout( this,3,5,"topLayout");
   topLayout->setMenuBar( mainMenu);
   QBoxLayout *box = new QHBoxLayout( topLayout );
   QBoxLayout* valuesLayout = new QVBoxLayout( box );

   //Forecast
   QGroupBox *gbForecast = new QGroupBox("Forecast", this);
   gbForecast->setColumnLayout(0, Qt::Vertical );
   QBoxLayout *gbForecastLayout = new QVBoxLayout(gbForecast->layout() );
   labForecastDate = new QLabel( "Date : 0000.00.00",gbForecast );
   labForecastTime = new QLabel( "Time : 00:00:00",gbForecast );
   labForecast = new QLabel( "Forecast : ?",gbForecast );
   labTendency = new QLabel( "Tendency : ?",gbForecast );
   gbForecastLayout->addWidget( labForecastDate );
   gbForecastLayout->addWidget( labForecastTime );
   gbForecastLayout->addWidget( labForecast );
   gbForecastLayout->addWidget( labTendency );
   valuesLayout->addWidget( gbForecast );
   //temperature
   QGroupBox *gbTemperature = new  QGroupBox (QString("Temperature")+_UNIT_TEMP, this);
   gbTemperature->setColumnLayout(0, Qt::Vertical );
   QBoxLayout *gbTemperatureLayout = new QVBoxLayout(gbTemperature->layout() );
   labTempMax = new QLabel( "Max : 00.0 at 00:00:00",gbTemperature );
   labTempMin = new QLabel( "Min : 00.0 at 00:00:00",gbTemperature );
   labTempOutside = new QLabel( "Outside : 00.0",gbTemperature );
   labTempInside = new QLabel( "Inside : 00.0",gbTemperature );
   gbTemperatureLayout->addWidget( labTempMax );
   gbTemperatureLayout->addWidget( labTempMin );
   gbTemperatureLayout->addWidget( labTempOutside );
   gbTemperatureLayout->addWidget( labTempInside );
   valuesLayout->addWidget( gbTemperature );

   //pressure
   QGroupBox *gbPressure = new QGroupBox(QString("Pressure")+_UNIT_PRESSURE, this);
   gbPressure->setColumnLayout(0, Qt::Vertical );
   QBoxLayout *gbPressureLayout = new QVBoxLayout(gbPressure->layout() );
   labAbsPressure = new QLabel( "Abs : ",gbPressure );
   labRelPressure = new QLabel( "Rel :",gbPressure );
   gbPressureLayout->addWidget( labAbsPressure );
   gbPressureLayout->addWidget( labRelPressure );
   valuesLayout->addWidget( gbPressure );

   //wind
   QGroupBox *gbWind = new QGroupBox("Wind", this);
   gbWind->setColumnLayout(0, Qt::Vertical );
   QBoxLayout *gbWindLayout = new QVBoxLayout(gbWind->layout() );
   labWindChill = new QLabel( "Chill",gbWind );
   labWindDirection = new QLabel( "Direction : ???",gbWind );
   labWindAngle = new QLabel( "Angle : ???",gbWind );
   labWindSpeed = new QLabel( "Speed : ???",gbWind );
   gbWindLayout->addWidget( labWindDirection );
   gbWindLayout->addWidget( labWindAngle );
   gbWindLayout->addWidget( labWindSpeed );
   gbWindLayout->addWidget( labWindChill );
   valuesLayout->addWidget( gbWind );

   //rain
   QGroupBox *gbRain = new QGroupBox(QString("Rainfall")+_UNIT_RAIN, this);
   gbRain->setColumnLayout(0, Qt::Vertical );
   QBoxLayout *gbRainLayout = new QVBoxLayout(gbRain->layout() );
   labRain1h = new QLabel( tr("1h"), gbRain );
   labRain24h = new QLabel( tr("24h"), gbRain );
   labRain1w = new QLabel( tr("Week"), gbRain );
   labRain1m = new QLabel( tr("Month"), gbRain );
   labRainTotal = new QLabel( tr("Total"), gbRain );
   gbRainLayout->addWidget( labRain1h );
   gbRainLayout->addWidget( labRain24h );
   gbRainLayout->addWidget( labRain1w );
   gbRainLayout->addWidget( labRain1m );
   gbRainLayout->addWidget( labRainTotal );
   valuesLayout->addWidget( gbRain );

   //Humidity
   QGroupBox *gbHumidity = new QGroupBox( tr("Humidity"), this);
   gbHumidity->setColumnLayout(0, Qt::Vertical );
   QBoxLayout *gbHumidityLayout = new QVBoxLayout(gbHumidity->layout() );
   labDewpoint = new QLabel( "Dewpoint",gbHumidity );
   labRelHumIn = new QLabel( "In",gbHumidity );
   labRelHumOut = new QLabel( "Out",gbHumidity );
   gbHumidityLayout->addWidget( labDewpoint);
   gbHumidityLayout->addWidget( labRelHumIn );
   gbHumidityLayout->addWidget( labRelHumOut );
   valuesLayout->addWidget( gbHumidity );

//QWidget::updateGeometry();

   QBoxLayout* views = new QVBoxLayout( box );
   QBoxLayout* icons = new QHBoxLayout( views );
   icons->addWidget( iconWind );
   icons->addWidget( iconTemp );
   icons->addWidget( iconForecast );
   icons->addWidget( iconBanner );


   tabViewWidget = new QTabWidget( this,"graphs");
   QWidget::updateGeometry();
   tabViewWidget->addTab( graphNow, "&Current" );
   tabViewWidget->addTab( graph24h, "&24 hours" );
   tabViewWidget->addTab( graphWeek, "&15 Days" );
   tabViewWidget->addTab( graphMonth, "&2 Months" );
   tabViewWidget->addTab( graphYear, "&Year" );
   tabViewWidget->addTab( graphCustom, "&Custom" );
   tabViewWidget->addTab( textView, "&Report" );
   views->addWidget( tabViewWidget );

   // status bar

   statusBar->setSizeGripEnabled ( true );
   statusBar->setFixedHeight ( 20 );
   statusStation = new QLabel( " Station ? ",this );
   statusDatabase = new QLabel( " Data base ? ",this );
   kledStation->setColor(Qt::white);
   kledDatabase->setColor(Qt::white);
   statusBar->addWidget(statusStation, 0, true );
   statusBar->addWidget(kledStation, 0, true );
   statusBar->addWidget(statusDatabase, 0, true );
   statusBar->addWidget(kledDatabase, 0, true );
   topLayout->addWidget(statusBar);


   topLayout->activate();

statusBar->message("Ready...");
}
/**
*  Get previous session
*  otherwise use default values from config.php
*/
void meteo2008Widget::sessionLoad()
{
   //statusBar->message("Getting session settings...");
    QSettings settings;
    settings.setPath( "imi21.com", "meteo2008" );
//stationUpdateInterval
  // stationUpdate=_STATION_UPDATE_MINUTES;
 stationUpdate = (int) settings.readNumEntry( "imi21.com/station/update", _STATION_UPDATE_MINUTES );
 //stationUpdate=_STATION_UPDATE_MINUTES;
}
/**
*  Save sessionp
*/
void meteo2008Widget::sessionSave()
{
    QSettings settings;
    settings.setPath( "imi21.com", "meteo2008" );

   settings.writeEntry( "imi21.com/database/localhost","mylocalhost" );
   settings.writeEntry( "imi21.com/database/user","myuser" );
   settings.writeEntry( "imi21.com/database/password","mypassword" );
   settings.writeEntry( "imi21.com/station/update",stationUpdate );
   settings.writeEntry( "imi21.com/metric/",true );
}
/**
   Menus and popmenus
*/

void meteo2008Widget::initMenu()
{
qDebug("Setting up Menu");
   setCaption ( "2008 Weather station");

   QPopupMenu* menuFile = new QPopupMenu;
   menuFile->insertItem( tr("&Quit"), this, SLOT(menuQuit()), CTRL+Key_Q );

   QPopupMenu* menuViews = new QPopupMenu;
   menuViews->insertItem( tr("&Enter custom range"), this,SLOT(menuCustomRange()));
   menuViews->insertSeparator ();
   menuViews->insertItem( tr("Print &report"), this, SLOT(menuStub()), CTRL+Key_R );

   menuViews->insertItem( tr("Print active &view"), this, SLOT(menuPrintView()), CTRL+Key_V );
//
   QPopupMenu* menuOptions = new QPopupMenu;
   menuOptions->insertItem( "Archive data", this, SLOT(menuArchiveData()) );
   menuOptions->insertItem( "Purge data", this, SLOT(menuPurgeData()) );
   menuOptions->insertItem( "Dump data", this, SLOT(menuStub()) );

   QPopupMenu* menuPublish = new QPopupMenu;

   menuPublish->insertItem( "Publish to web &site", this, SLOT(menuPublishWebsite()) );
   menuPublish->insertItem( "Publish to &Wundergrund", this, SLOT(menuPublishWundergrund()) );
   menuPublish->insertItem( "Publish banner", this, SLOT(menuStub()) );
// 
   QPopupMenu* menuConfig = new QPopupMenu;
   menuConfig->insertItem( "&Station settings", this, SLOT(menuStationDlg()) );
   menuConfig->insertItem( "&Database settings", this, SLOT(menuDatabaseDlg()) );
   menuConfig->insertItem( "&FTP settings", this, SLOT(menuFtpDlg()) );
   menuConfig->insertItem( "&Wundergrund settings", this, SLOT(menuWundergrundDlg()) );
   menuConfig->insertItem( "&Path settings", this, SLOT(menuPathDlg()) );
   menuConfig->insertItem( "&Auto settings", this, SLOT(menuAutoDlg()) );
//
   QPopupMenu* menuHelp = new QPopupMenu;
   menuHelp->insertItem( "&Information", this, SLOT(menuStub()) );
   menuHelp->insertItem( "&About", this, SLOT(menuAbout()) );

   mainMenu = new QMenuBar( this );
   Q_CHECK_PTR( mainMenu );
   mainMenu->insertItem("&File", menuFile);
   mainMenu->insertItem("&Views", menuViews);
   mainMenu->insertItem("&Options", menuOptions);
   mainMenu->insertItem("&Publish data", menuPublish);
   mainMenu->insertItem("&Configuration", menuConfig);
   mainMenu->insertItem("&Update now", this, SLOT(timerRequest()));
   mainMenu->insertItem("&Help", menuHelp);
}
/**
   Slots for menus and popmenus
*/
void meteo2008Widget::menuStub()
{
statusBar->message( tr("Menu stub") );
        QMessageBox::message("Menu stub", "This option is not yet implemented");
}

void meteo2008Widget::menuQuit()
{
   sessionSave();
   statusBar->message( tr("Quit") );
        QMessageBox::message("Menu stub", "This option is not yet implemented");
}

void meteo2008Widget::menuCustomRange()
{
statusBar->message( tr("Menu stub") );
        QMessageBox::message("Menu stub", "This option is not yet implemented");
}

void meteo2008Widget::menuArchiveData()
{
   statusBar->message( tr("Archiving database") );
   kledDatabase->setColor(Qt::yellow);
   if (database->archiveData())
   {
      kledDatabase->setColor(Qt::green);
      statusBar->message( tr("Archiving ok"), 2000 );
      updateGraph();
   }else
   {
      kledDatabase->setColor(Qt::red);
      statusBar->message( tr("Archiving failed"), 2000 );
   }
}
void meteo2008Widget::menuPurgeData()
{
   statusBar->message( tr("Purging database") );
   kledDatabase->setColor(Qt::yellow);
   if (database->purgeOldData())
   {
      kledDatabase->setColor(Qt::green);
      statusBar->message( tr("Purging ok"), 2000 );
   }else
   {
      kledDatabase->setColor(Qt::red);
      statusBar->message( tr("Purging failed"), 2000 );
   }
}


void meteo2008Widget::menuStationDlg()
{
   qDebug("Station Dialog");
   statusBar->message( tr("Station Configuration"), 2000 );
   StationDlg *stationDlg=new StationDlg(this);
   stationDlg->setStationUpdate(stationUpdate);

   if ( stationDlg->exec() == QDialog::Accepted ) {
      stationUpdate = stationDlg->stationUpdateRate();
      timer->changeInterval( (1000*60*stationUpdate) );
   }

   delete stationDlg;
}
void meteo2008Widget::menuDatabaseDlg()
{
   qDebug("Database Dialog");
   statusBar->message( tr("Database Configuration"), 2000 );
   DatabaseDlg *databaseDlg=new DatabaseDlg(this);
   databaseDlg->exec();
   delete databaseDlg;
}
void meteo2008Widget::menuFtpDlg()
{
   qDebug("Ftp Dialog");
   statusBar->message( tr("Ftp Configuration"), 2000 );
   FtpDlg *ftpDlg=new FtpDlg(this);
   ftpDlg->exec();
   delete ftpDlg;
}
void meteo2008Widget::menuWundergrundDlg()
{
   qDebug("Wundergrund Dialog");
   statusBar->message( tr("Wundergrund Configuration"), 2000 );
   WundergrundDlg *wundergrundDlg=new WundergrundDlg(this);
   wundergrundDlg->exec();
   delete wundergrundDlg;
}

void meteo2008Widget::menuPathDlg()
{
   qDebug("Path Dialog");
   statusBar->message( tr("File path Configuration"), 2000 );
   PathDlg *pathDlg=new PathDlg(this);
   pathDlg->exec();
   delete pathDlg;
}
void meteo2008Widget::menuAutoDlg()
{
   qDebug("Automatic setting Dialog");
   statusBar->message( tr("Automatic Configuration"), 2000 );
   AutoDlg *autoDlg=new AutoDlg(this);
   autoDlg->exec();
   delete autoDlg;
}

/**
* www.wunderground.com
* Publish latest data to the Wundergrund site
*/
void meteo2008Widget::menuPublishWundergrund()
{
float tempf,dewptf,windgustmph,rainin,dailyrainin,baromin,humidity;
int windspeedmph,winddir;
QString sdate,stime , weather,clouds;

statusBar->message( tr("Publishing to Wundergrund"), 2000 );

sdate=stationdata->date();
stime=stationdata->time();
tempf=stationdata->tempOut();
dewptf=stationdata->dewpoint();
humidity=QString(stationdata->relHumOut()).toInt();
windspeedmph= (int) stationdata->windSpeed();
winddir=  (int) stationdata->windAngle();
windgustmph=0.00;
rainin=QString( stationdata->rain1h() ).toFloat();
dailyrainin=QString( stationdata->rain24h() ).toFloat();
baromin=QString(stationdata->relPressure()).toFloat();
if (_METRIC) // convert the metric stuff to imperial format
{
 qDebug("Is metric so converting");
 tempf=((tempf *9) /5 ) +32;
 dewptf=(( dewptf *9 ) /5 ) +32;
 baromin=baromin/33.86;
rainin=rainin*0.0394;
dailyrainin=dailyrainin*0.0394;
 windspeedmph=(int) (windspeedmph * 0.621371192237334);
}

QString httpRequest=QString("%1%2").arg( _WUNDERGRUND_URL).arg(_WUNDERGRUND_PATH);
httpRequest+=QString("?action=updateraw");
httpRequest+=QString("&ID=%1&PASSWORD=%2").arg(_WUNDERGRUND_ID).arg(_WUNDERGRUND_PASSWORD);
httpRequest+=QString("&dateutc=%1+%2").arg(sdate).arg(stime);
httpRequest+=QString("&tempf=%1&dewptf=%2").arg(tempf,0,'f',0).arg(dewptf,0,'f',2);
httpRequest+=QString("&humidity=%1").arg(humidity);
httpRequest+=QString("&baromin=%1").arg(baromin,0,'f',2);
httpRequest+=QString("&windspeedmph=%1&winddir=%2").arg(windspeedmph).arg(winddir);
httpRequest+=QString("&rainin=%1").arg(rainin,0,'f',2);
httpRequest+=QString("&dailyrainin=%1").arg(dailyrainin,0,'f',2);
httpRequest+=QString("&softwaretype=%1").arg(_WUNDERGRUND_SOFTWARE);

qInitNetworkProtocols ();

QUrlOperator *op= new QUrlOperator( httpRequest );
op->get();

qDebug( httpRequest );
statusBar->message( tr("Finished publishing to Wundergrund"), 2000 );
}

/**
   Save the data to a PHP file located in _FTP_PHP_FILE
   open FTP connection and upload the file to _HTML_PATH
*/
void meteo2008Widget::menuPublishWebsite()
{
   statusBar->message( tr("Saving and publishing web files"), 2000 );

QString file=QString ("%1%2").arg(_FTP_LOCAL_FILES).arg(_FTP_PHP_FILE);

  QFile f( file );
    if ( !f.open( IO_WriteOnly ) )
        return;
    QTextStream t( &f );


    t.setEncoding(QTextStream::UnicodeUTF8);
    t << "<?php" <<  "\n /* meteo2008 data */\n";
    t << "$location=\"" << _BANNER_LOCATION << "\";\n";
    t << "$manager=\"" << _BANNER_MANAGER << "\";\n";
    t << "$date=\"" << stationdata->date() << " " <<  stationdata->time() << "\";\n";
    t << "$temp_out=\"" << stationdata->tempOut() << "\";\n";
    t << "$tempMax=\"" << stationdata->tempMax() << "\";\n";
    t << "$tempMaxTime=\"" << stationdata->tempMaxTime() << "\";\n";
    t << "$tempMin=\"" << stationdata->tempMin() << "\";\n";
    t << "$tempMinTime=\"" << stationdata->tempMinTime() << "\";\n";
    t << "$wind_direction=\"" << stationdata->windDirection() << "\";\n";
    t << "$wind_angle=\"" << stationdata->windAngle() << "\";\n";
    t << "$wind_speed=\"" << stationdata->windSpeed( ) << "\";\n";
    t << "$wind_chill=\"" << stationdata->windChill( ) << "\";\n";
    t << "$abs_pressure=\"" << stationdata->absPressure( ) << "\";\n";
    t << "$rel_pressure=\"" << stationdata->relPressure( ) << "\";\n";
    t << "$rel_dewpoint=\"" << stationdata->dewpoint() << "\";\n";
    t << "$rel_humidity=\"" << stationdata->relHumOut() << "\";\n";
    t << "$rain_1h=\"" << stationdata->rain1h( ) << "\";\n";
    t << "$rain_24h=\"" << stationdata->rain24h( ) << "\";\n";
    t << "$rain_1w=\"" << stationdata->rain1w( ) << "\";\n";
    t << "$rain_1m=\"" << stationdata->rain1m( ) << "\";\n";
    t << "$rain_total=\"" << stationdata->rainTotal( ) << "\";\n";
    t << "$tendency=\"" << stationdata->tendency( ) << "\";\n";
    t << "$forecast=\"" << stationdata->forecast( ) << "\";\n";
    t << "?>" <<  "\n";
f.close();


statusBar->message( "Dumping data files completed" );

/*****************************/

qDebug("Setting up ftp transaction");
ftp->clearList();
ftp->addFile(QString("%1%2").arg(_FTP_LOCAL_FILES).arg(_FTP_PHP_FILE));
ftp->addFile(QString("%1%2").arg(_FTP_LOCAL_FILES).arg(_FTP_BANNER));
ftp->addFile(QString("%1%2").arg(_FTP_LOCAL_FILES).arg(_FTP_WIND));
ftp->addFile(QString("%1%2").arg(_FTP_LOCAL_FILES).arg(_FTP_TEMPERATURE));
ftp->connectToHost();


statusBar->message( "Uploading data files to web server completed" );
   //delete ftp;
}
/**
   Prints the selected tab view
*/
void meteo2008Widget::menuPrintView()
{
   if ( printer->setup( this ) )
   {
      QPainter p(printer);
      printer->setColorMode(QPrinter::Color);
      printer->setOrientation (QPrinter::Landscape);
      printer->setDocName(QString(_BANNER_TITLE));
      printer->setFullPage(FALSE);

      QPixmap pm = QPixmap::grabWidget( graph24h );
      p.drawPixmap(0, 0, pm);
   }
}
/**
   Simply about box
*/
void meteo2008Widget::menuAbout()
{
    QMessageBox::about( this, "About meteo2008",
        "Opensource software published under GPL v2\n\n"
        "Copyright Phillip Aldridge\n"
        "http://www.imi21.com/meteo2008/\n" );
}
/**


*/
void meteo2008Widget::message(QString m)
{
textView->append(m);
}
#include "meteo2008widget.moc"

